package com.xunyi.learndemo.service;

import com.xunyi.learndemo.domain.OrderInfo;
import com.xunyi.learndemo.mapper.OrderInfoMapper;
import io.netty.util.HashedWheelTimer;
import io.netty.util.TimerTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class OrderTimeoutService {

    private static final long ORDER_TIMEOUT = 30; // 30分钟

    @Autowired
    private HashedWheelTimer timer;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    // 添加订单超时任务
    public void addDelayTask(OrderInfo order) {
        TimerTask task = timeout -> {
            try {
                OrderInfo currentOrder = orderInfoMapper.selectOrderInfoById(order.getId());
                if (currentOrder != null && currentOrder.getOrderStatus().equals(OrderService.OrderStatus.UNPAID.name())) {
                    currentOrder.setOrderStatus(OrderService.OrderStatus.CANCELED.name());
                    orderInfoMapper.updateOrderInfo(currentOrder);
                    System.out.println("Order " + order.getOrderNum() + " has been canceled due to timeout.");
                }
            } catch (Exception e) {
                // 异常处理与日志记录
                e.printStackTrace();
            }
        };
        timer.newTimeout(task, ORDER_TIMEOUT, TimeUnit.MINUTES);
    }
}